<?php

/**
 * @classname 基础
 * @classaccess public
 * @decription 基础接口
 * @author 张旭刚
 * @updateTime 2020年05月12日
 */

namespace console\controllers;

use Yii;

class TaskController extends PublicController {
    
    private $completeKey;
    
    public function __construct($id, $module, $config = array()) {
        parent::__construct($id, $module, $config);
        $this->completeKey = $this->setting('hash_processs_completed_key');//处理完成
    }


    /**
     * @see 欢迎词
     * @describe 这个接口只是返回一个欢迎词，可以用来验证环境搭建是否成功
     * @access public
     * @name queue
     * @method POST
     * @requestType FORM
     * @defget no
     * @author 张旭刚,2019年10月31日,创建
     * 
     * @header guid|string|required|客户端唯一编号
     * 
     * @return welcome|string|欢迎词
     */
    public function actionQueue() {
        $queue = Yii::$app->rabbitmq->getQueue('queue_huawei');
        echo "开始处理排队消息：\n";
        while (true) {
            $queue->consume(function($envelope, $queue) {//此处调用业务逻辑处理方法
                $this->processMessage($envelope, $queue);
            });
            //$q->consume('processMessage', AMQP_AUTOACK); //自动ACK应答
        }
        $queue->disconnect();
    }
    
    private function processMessage ($envelope, $queue) {
        $msg = $envelope->getBody();
        $data = $this->Queue($msg);
        if($data['result'] == 'success'){
            echo '队列：' . $data['data']['queueKey'] . "排队成功\n";
        }elseif($data['result'] == 'repeat'){
            echo '队列：' . $data['data']['queueKey'] . "因已存在排队成功且未核销的排队信息，本次排队失败\n";
        }
        $queue->ack($envelope->getDeliveryTag()); 
    }

    private function Queue($msg){
        $data = unserialize($msg);
        $d = unserialize($this->redis->hget($this->completeKey, $data['queueKey']));
        if(!empty($d)){return ['result' => 'repeat', 'data' => $d];}
        $data['queueNo'] = $this->getQueueNumber();
        $data['status'] = 1;
        $data['useStatus'] = 0;
        $data['success_at'] = time();
        $this->redis->hset($this->completeKey, $data['queueKey'], serialize($data));
        return ['result' => 'success', 'data' => $data];
    }

    /**
     * 取得排队号
     * @return type
     */
    private function getQueueNumber(){
        $prefix = $this->setting('queue_number_prefix');
        $cacheKey = 'queue_total';
        $total = $this->redis->get($cacheKey);
        $current = $total + 1;
        $this->redis->set($cacheKey, $current);
        $len = strlen((string)$current);
        $maxLen = $this->setting('queue_number_length');
        $str  = '';
        for($i = 0; $i < $maxLen - $len; $i++){
            $str .= '0';
        }
        return $prefix.$str.$current;
    }

}
